package com.base.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.base.result.ResponseResult;
import com.base.result.ResponseResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.po.voip.Urlconfig;
import com.base.po.voip.UrlconfigExample;
import com.base.po.voip.Users;
import com.base.service.SelfShopService;
import com.base.service.UrlconfigService;
import com.base.service.UsersService;
import com.base.utils.PasswordUtils;

@Controller
@RequestMapping("/admin")
public class AdminIndexController {

    private final UsersService adminUserService;

    private final UrlconfigService urlconfigService;

    private final SelfShopService selfShopService;

    private final RedisTemplate<String, Object> redisTemplate;

    private final static String dir = "WEB_USER_INFO:";

    public AdminIndexController(UsersService adminUserService,
                                UrlconfigService urlconfigService,
                                SelfShopService selfShopService,
                                RedisTemplate<String, Object> redisTemplate) {
        this.adminUserService = adminUserService;
        this.urlconfigService = urlconfigService;
        this.selfShopService = selfShopService;
        this.redisTemplate = redisTemplate;
    }

    // 后台登录
    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult checkAdmin(HttpSession session, String useracc, String userpwd) throws Exception {

        Users users = adminUserService.selectByUsername(useracc);
        if (users == null || "".equals(userpwd)) {
            return ResponseResultUtils.getResponseResultF("账号不存在");
        }
        // 得到启用状态
        boolean state = users.getDatastatus();
        if (!state) {
            return ResponseResultUtils.getResponseResultF("账号被冻结");
        }
        if (!PasswordUtils.decodePWD(userpwd, users.getPassword())) {
            return ResponseResultUtils.getResponseResultF("密码错误");
        }
        session.setAttribute("isLTH", 0);//1.淘惠 0.淘惠
        session.setAttribute("adminparentid", users.getParentid());
        session.setAttribute("useracc", useracc);
        session.setAttribute("userNick", users.getUsername());
        session.setAttribute("adminUserId", users.getId());
        session.setAttribute("adminUsergrade", users.getRole());
        session.setAttribute("adminAddcard", users.getAddcard());
        session.setAttribute("adminAirreCharge", users.getAirrecharge());
        session.setAttribute("agentLogo", users.getAgentlogo());
        session.setAttribute("theme", StringUtils.isEmpty(users.getTheme()) ? 0 : users.getTheme());// 查看财务信息权限

        Map<String, Object> map = new HashMap<>();
        if (users.getRole() == 1) {/*代理商*/
            map.put("parentId", users.getId());
            map.put("superiorParentId", users.getParentid());/*""*/
            map.put("shopId", users.getId());
        }
        if (users.getRole() == 2) {/*商家*/
            map.put("parentId", users.getParentid());
            map.put("superiorParentId", users.getParentid());
            map.put("shopId", users.getId());
        }
        map.put("role", users.getRole());
        redisTemplate.opsForValue().set(dir + session.getId(), JSON.toJSONString(map), 180, TimeUnit.MINUTES);
        return ResponseResultUtils.getResponseResultS("登录成功");

    }

    // 用于用户退出登陆以及切换账号，用户登陆页面
    @RequestMapping("/login/{name}")
    public ModelAndView login1(HttpServletRequest request, @PathVariable String name) {
        request.getSession().invalidate();
        ModelAndView modelAndView = new ModelAndView(); // 数据
        // 获取代理商名称
        UrlconfigExample urlconfigExample = new UrlconfigExample();
        urlconfigExample.getOredCriteria().add(urlconfigExample.createCriteria().andPinyinEqualTo(name));
        List<Urlconfig> agentUrl = urlconfigService.selectByExample(urlconfigExample);
        String titleName = "未获取到登录账户信息";
        if (agentUrl != null && agentUrl.size() != 0) {
            titleName = adminUserService.selectByPrimaryKey(agentUrl.get(0).getOemid()).getUsername();
            request.getSession().setAttribute("titleName", titleName); // 代理商名称
        }
        request.getSession().setAttribute("titleId", name); // 登录标题));
        // 设置页面进行跳转
        modelAndView.setViewName("jsp/login");
        return modelAndView;
    }

    // 用于用户退出登陆以及切换账号，用户登陆页面
    @RequestMapping("/login")
    public ModelAndView login2(HttpServletRequest request) {
        redisTemplate.delete(dir + request.getSession().getId());
        request.getSession().invalidate();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("jsp/login");
        return modelAndView;
    }

    @RequestMapping("/loginCheck1")
    public void loginCheck1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        //设置跳转地址
        response.setHeader("redirectUrl", "/SbdVoip/jsp/loginCheck2.jsp");
        //设置跳转使能
        response.setHeader("enableRedirect","true");
        response.flushBuffer();
    }

    // 用户首页
    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) throws Exception {
        String userId = (String) request.getSession().getAttribute("adminUserId"); // 登录的用户ID
        Integer isXTService = (Integer) request.getSession().getAttribute("isXTService");
        Integer isLTH = (Integer) request.getSession().getAttribute("isLTH");
        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // 设置页面进行跳转
        if (userId.equals("0b8a2f00271e40b9aea750264bf1bb58") || isLTH == 1) {
            modelAndView.setViewName("jsp/admin_index_lth");
        } else {
            if (isXTService != null && isXTService == 1) {
                modelAndView.setViewName("jsp/admin_index_xt");
            } else if (isXTService != null && isXTService == 2) {
                modelAndView.setViewName("jsp/admin_index_xt2");
            } else {
                modelAndView.setViewName("jsp/admin_index");
            }
        }

        return modelAndView;
    }
}
